package com.zf.nospring.rocketmq.batch;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量发送消息，每个批次大小不能超过4MB
 */
public class BatchProducerTest {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建生产者，指定生产者所属的组
        DefaultMQProducer producer = new DefaultMQProducer("no-spring-pg");
        // 指定NameServer的地址
        producer.setNamesrvAddr("localhost:9876");
        // 启动生产者
        producer.start();
        ArrayList<Message> messages = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            Message message = new Message("test_topic", ("批量消息" + i).getBytes());
            messages.add(message);

        }

        //把大的消息分裂成若干个小的消息，每个部分不超过4MB
        ListSplitter splitter = new ListSplitter(messages);
        while (splitter.hasNext()) {
            try {
                List<Message> listItem = splitter.next();
                // 批量发送消息
                producer.send(listItem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 单独处理大于4MB的消息
        List<Message> gt4MbMsgList = splitter.getGt4MbMsg();
        for (Message message : gt4MbMsgList) {
            producer.send(message);
        }


        // 关闭生产者
        producer.shutdown();
    }
}
